package cn.luyifushi.sys.controller;

import cn.luyifushi.config.redis.service.RedisService;
import cn.luyifushi.utils.Result;
import cn.luyifushi.utils.VerifyCode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author sword-l
 * @version 1.0.0
 * @title CaptchaController
 * @description
 **/
@RestController
@RequestMapping("/api/login")
public class CaptchaController {

    @Resource
    private RedisService redisService;

    @GetMapping("/captcha")
    public Result getCaptcha(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        VerifyCode verifyCode = new VerifyCode();
        BufferedImage image = verifyCode.getImage();
        String text = verifyCode.getText();
        String uuid= UUID.randomUUID().toString();
        String codeKey = "captcha_key_"+ uuid ;
        redisService.set(codeKey,text,60L);
        // 将 BufferedImage 转换为 base64 字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        Map<String,Object> imgResult = new HashMap<String,Object>(2){{
            put("img", base64Image);
            put("captcha_id",uuid);
        }};
        return Result.ok(imgResult);
    }
}
